<template>
  <div>
    <s-header :name='"地址管理"'/>
    <van-address-list
      v-model="chosenAddressId"
      :list="addressList"
      default-tag-text="默认"
      @add="onAdd"
      @edit="onEdit"
      @select="onSelect"
      />
  </div>
</template>

<script>
import { mapGetters } from 'vuex';

import { getAddressByUserId, updateAddressIsFlag } from '@/api/address'
import  sHeader  from '@/components/SHeader';


export default {
  name: 'addressManage',
  data() {
    return {
      addressList: [],
      chosenAddressId: '',
      from: this.$route.query.from ? this.$route.query.from : null
    }
  },
  
  created() {
    this.onLoad()
  },
  components: {
    sHeader,
  },
  computed: {
    ...mapGetters(['id'])
  },
  methods: {
    onLoad() {
      getAddressByUserId(this.id).then(res => {
        if(res.code === 200){
          this.addressList = res.data;
          this.addressList.map(item => {
            item.name = item.userName;
            item.tel = item.userPhone;
            item.address = item.provinceName + item.cityName + item.countyName + item.detailAddress;
            item.isDefault = item.defaultFlag;
          })

        }
      })
    },
    onAdd() {
      this.$router.push({
        path: '/address-edit',
        query: {type: 'add'}
      })
    },
    onSelect(item) {
      updateAddressIsFlag({
        addressId: item.id,
        userId: this.id
      })
      if(this.from === 'create-order') {
        this.$router.push({
          path: '/create-order',
          query: { addressId: item.id,}
        })
      }
      // this.$router.push({
      //   path: '/address-edit',
      //   query: {type: 'add'}
      // })
    },
    onEdit(val) {
      this.$router.push({
        path: '/address-edit',
        query: {type: 'edit', addressId: val.id}
      })
    },
    onClickLeft() {
      this.$router.go(-1)
    },
  }
}
</script>

<style lang="scss" scoped>
  .block {
    height: 50px;
  }
</style>